import Toast from '@vant/weapp/toast/toast';
const app = getApp();

Page({
  data: {
    phone: '',
    newPassword: '',
    email: '',
    verificationCode: '',
    phoneError: '',
    newPasswordError: '',
    emailError: '',
    verificationCodeError: '',
    showNewPassword: false,
    sendCodeDisabled: false,
    sendCodeText: '发送验证码',
    countdown: 60,
  },

  onLoad: function (options) {

  },

  toHome:()=>{
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  onPhoneChange: function (e) {
    const value = e.detail;
    this.setData({
      phone: value,
      phoneError: this.validatePhone(value) ? '' : '手机号格式不正确'
    });
  },

  onNewPasswordChange: function (e) {
    const value = e.detail;
    this.setData({
      newPassword: value,
      newPasswordError: this.validatePassword(value) ? '' : '新密码(6-16位)'
    });
  },

  onEmailChange: function (e) {
    const value = e.detail;
    this.setData({
      email: value,
      emailError: this.validateEmail(value) ? '' : '邮箱格式不正确'
    });
  },

  onVerificationCodeChange: function (e) {
    const value = e.detail;
    this.setData({
      verificationCode: value,
      verificationCodeError: this.validateVerificationCode(value) ? '' : '验证码需6位数字'
    });
  },

  // 拆分校验方法
  validatePhone: function (value) {
    return value && /^1[3-9]\d{9}$/.test(value);
  },

  validatePassword: function (value) {
    return value && value.length >= 6 && value.length <= 16;
  },

  validateEmail: function (value) {
    return value && /^[\w.-]+@[\w.-]+\.\w+$/.test(value);
  },

  validateVerificationCode: function (value) {
    return value && value.length === 6 && /^\d+$/.test(value);
  },

  toggleNewPasswordVisibility: function () {
    this.setData({
      showNewPassword: !this.data.showNewPassword
    });
  },

  validateInput: function () {
    const { phone, newPassword, email, verificationCode } = this.data;
    return this.validatePhone(phone) &&
      this.validatePassword(newPassword) &&
      this.validateEmail(email) &&
      this.validateVerificationCode(verificationCode);
  },

  sendVerificationCode: function () {
    const { email } = this.data;
    if (!email) {
      this.setData({ emailError: '邮箱必填' });
      return;
    } else if (!/^[\w.-]+@[\w.-]+\.\w+$/.test(email)) {
      this.setData({ emailError: '邮箱格式不正确' });
      return;
    }

    this.setData({ sendCodeDisabled: true });
    let countdown = this.data.countdown;
    const timer = setInterval(() => {
      if (countdown > 0) {
        countdown--;
        this.setData({ sendCodeText: `重新发送(${countdown}s)` });
      } else {
        clearInterval(timer);
        this.setData({
          sendCodeDisabled: false,
          sendCodeText: '发送验证码',
          countdown: 60,
        });
      }
    }, 1000);

    wx.request({
      // url: 'https://kf.webxyq.com/emailValidCode',  // [!code --]
      url: 'https://kf.webxyq.com/emailValidCode',    // [!code ++]
      method: 'POST',
      data: {
        appkey: app.globalData.appkey,
        email: email
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      success: (res) => {
        console.log(res);
        if (res.statusCode === 200) {
          Toast.success('验证码发送成功');
        } else {
          Toast.fail(res.data.msg || '验证码发送失败');
          clearInterval(timer);
          this.setData({
            sendCodeDisabled: false,
            sendCodeText: '发送验证码',
            countdown: 60,
          });
        }
      },
      fail: () => {
        Toast.fail('网络请求失败');
        clearInterval(timer);
        this.setData({
          sendCodeDisabled: false,
          sendCodeText: '发送验证码',
          countdown: 60,
        });
      }
    });
  },

  onSubmit: function () {
    if (!this.validateInput()) {
      return;
    }

    const { phone, newPassword, email, verificationCode } = this.data;

    wx.request({
      url: 'https://kf.webxyq.com/checkValidCode',
      method: 'POST',
      data: {
        appkey: app.globalData.appkey,
        validCode: verificationCode
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      success: (res) => {
        console.log(res);
        if (res.data.code === 'K001') {
          wx.request({
            url: 'https://kf.webxyq.com/retrievePassword',
            method: 'POST',
            data: {
              appkey: app.globalData.appkey,
              phone: phone,
              password: newPassword,
              email: email  // 新增邮箱参数
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            },
            success: (res) => {
              if (res.data.code === 'L001') {
                Toast.success('密码找回成功');
                setTimeout(() => {
                  wx.redirectTo({
                    url: '/pages/login/login',
                  });
                }, 1500);
              } else {
                Toast.fail(res.data.msg || '密码找回失败');
              }
            },
            fail: () => {
              Toast.fail('网络请求失败');
            }
          });
        } else {
          this.setData({ verificationCodeError: res.data.msg || '验证码不正确' });
          Toast.fail(res.data.msg || '验证码验证失败');
        }
      },
      fail: () => {
        Toast.fail('网络请求失败');
      }
    });
  },

  goToLogin: function () {
    wx.redirectTo({
      url: '/pages/login/login',
    });
  }
})